<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button size="small" type="danger" @click="exportEmp">excel导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="头像">
            <template slot-scope="{row}">
              <img :src="row.staffPhoto" alt="" style="width:80%">
            </template>
          </el-table-column>
          <el-table-column
            label="聘用形式"
            sortable=""
            :formatter="formatter"
            prop="formOfEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState" />
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button

                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="emitRole(row.id)">角色</el-button>
              <el-button
                v-if="checkPermission('del')"
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page="page.page"
          :total="page.total"
          @current-change="changePage"
        />
      </el-row>

      <!-- 弹框 -->
      <add-employee :show-dialog.sync="showDialog" />
      <!-- 角色弹框 -->
      <assignRole ref="roleRef" :show-role-dialog.sync="showRoleDialog" :user-id="userId" /></assignrole>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import employee from '@/api/constant/employees'
import addEmployee from './add-employee/index.vue'
import assignRole from './assign-role'
import { formatDate } from '@/filters'

export default {
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      list: [], // 员工列表
      userId: '', // 用户id
      page: {
        page: 1, // 页码
        size: 10, // 页数
        total: 0
      },
      loading: false, // 加载状态
      showDialog: false,
      showRoleDialog: false // 角色弹框
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 弹框
    async emitRole(id) {
      this.userId = id // 当前用户id
      await this.$refs.roleRef.getUserDetailById(id)
      this.showRoleDialog = true
    },
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList(this.page)
    },
    // row行数据  column 列对象  cellValue 单元格数据 index 下标
    formatter(row, column, cellValue, index) {
      const result = employee.hireType.find((item) => item.id === cellValue * 1)
      return result && result.value ? result.value : '未知'
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('确定删除吗?')
        // 删除当前员工
        await delEmployee(id)
        // 重新获取员工列表
        this.getEmployeeList()
        this.$message.success('成功删除')
      } catch (error) {
        console.log(error)
      }
    },
    // 导出员工
    exportEmp() {
      import('@/vendor/Export2Excel').then(async(excel) => {
        const headers = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }
        // 加载所有员工列表数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })

        // 接口数据是[对象]  转换成[数组]  [['张傲', 18], ['董晓晔', 17]]

        const data = this.formatJSON(headers, rows)

        // 数据的处理

        // console.log(excel, 'excel')
        excel.export_json_to_excel({
          // multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']], // 复杂表头
          // merges: ['A1:A2', 'B1:F1', 'G1:G2'], // 合并单元格
          header: Object.keys(headers), // 表格头
          data, // 表格体数据
          filename: '员工列表',
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2']
        })
      })
    },
    formatJSON(headers, list) {
      return list.map((item) => {
        return Object.keys(headers).map((key) => {
          if (headers[key] === 'correctionTime' || headers[key] === 'timeOfEntry') {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const result = employee.hireType.find((emp) => emp.id === item[headers[key]])

            return result ? result.value : '未知'
          }
          return item[headers[key]]
        })
      })
    }
  }
}
</script>

<style></style>
